package com.bankcomm.luafuction;

import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.keplerproject.luajava.LuaException;
import org.keplerproject.luajava.LuaObject;
import org.keplerproject.luajava.LuaState;

import android.database.sqlite.SQLiteDatabase;

import com.bankcomm.common.ConfigManager;
import com.rytong.tools.datastorage.PackageManagerAndroid;
import com.rytong.tools.datastorage.SqlDb;
import com.rytong.tools.ui.Component;
import com.rytong.tools.utils.Utils;

public class LuaDatabase {
    private SqlDb dbHelper_;

    public LuaDatabase() {
        // TODO Auto-generated constructor stub
        try {
            dbHelper_ = new SqlDb(ConfigManager.currentView_, "database.sql", null, 1);
            Component.LUASTATE.pushObjectValue(this);
            Component.LUASTATE.setGlobal("luadatabase");
            String luahead = "database = {};";
            String open = "function database:open(name) local a1 = luadatabase:open(name); return a1; end;";
            String close = "function database:close(database) luadatabase:close(database); end;";
            String exec = "function database:exec(database,sql) return luadatabase:exec(database,sql); end;";
            String add = "function database:addData(key, value) luadatabase:addData(key, value); end;";
            String insert = "function database:insertData(key, value) luadatabase:insertData(key, value); end;";
            String update = "function database:updateData(key, value) luadatabase:updateData(key, value); end;";
            String get = "function database:getData(key) local a1 = luadatabase:getData(key); return a1; end;";
            String delete = "function database:deleteData(key) local a1 = luadatabase:deleteData(key); return a1; end;";
          
            String saveSP = "function database:saveSP(key, value) luadatabase:saveSP(key, value); end;";
            String getSP = "function database:getSP(key) local a1 = luadatabase:getSP(key); return a1; end;";
            Component.LUASTATE.gc(LuaState.LUA_GCCOLLECT, 0);
            Component.LUASTATE.LdoString(luahead.concat(open).concat(close).concat(exec).concat(add).concat(insert)
                    .concat(update).concat(get).concat(delete).concat(saveSP).concat(getSP));
        } catch (Exception e) {
            Utils.printException(e);
        }
    }

    /**
     * 打开数据库，如果没有则建立一个新的数据库。（只建立数据库，但不建立表）
     * 
     * @param name
     *            数据库名
     * @return 当前数据库对象，失败则返回nil
     */
    public Object open(String name) {
        SqlDb dbHelper = new SqlDb(ConfigManager.currentView_, name, null, 1);
        return dbHelper;
    }

    /**
     * 关闭数据库
     * 
     * @param obj
     *            数据库对象
     */
    public void close(Object obj) {
    	try{
    		if (obj instanceof SqlDb) {
                SqlDb dbhelper = (SqlDb) obj;
                dbhelper.close();
            }
    	}catch(Exception e){
    		Utils.printException(e);
    	}
    }
    
    public Object exec(Object obj,String sql) {
    	Object finalResult = null; // 返回的最终结果。
        if (sql != null && obj instanceof SqlDb) {
        	SqlDb dbhelper = (SqlDb) obj;
            SQLiteDatabase database = dbhelper.getWritableDatabase();
            sql = sql.toLowerCase();
        	if(sql.startsWith("select")){
        		try{
        			List<Map<String,String>> result = dbhelper.executeQuery(database , sql);
        			
					// 创建一个table
					Component.LUASTATE.newTable();
					LuaObject tableTemp = Component.LUASTATE.getLuaObject(-1);
					Component.LUASTATE.pop(1);
					// 将约定的固有参数压入表中
					tableTemp.push();

					for(int n=0 ; n < result.size(); n++){
						Set<String> set = result.get(n).keySet();
						Iterator<String> iterator = set.iterator();
						
						Component.LUASTATE.newTable();
						LuaObject tableItem = Component.LUASTATE.getLuaObject(-1);
						Component.LUASTATE.pop(1);
						tableItem.push();
						
						while(iterator.hasNext()){
							String key = iterator.next();
							Component.LUASTATE.pushObjectValue(key);
							Component.LUASTATE.pushObjectValue(result.get(n).get(key));
							Component.LUASTATE.setTable(-3);
						}
						
						tableTemp.push();
						Component.LUASTATE.pushObjectValue(n);
						Component.LUASTATE.pushObjectValue(tableItem);
						Component.LUASTATE.setTable(-3);
					}
					finalResult = tableTemp;
        		} catch(LuaException luae){
        			Utils.printException(luae);
        		} catch(Exception e){
        			Utils.printException(e);
        		}
        	} else {
        		String errorCode = dbhelper.exec(database, sql);
        		if(errorCode != null && !"".equals(errorCode)){
        		// 返回错误信息。错误信息包含提示和sql语句，只要提示，不要sql语句。
        		errorCode = errorCode.replace(sql, "");
        		// 并且去掉提示的冒号。
        		errorCode = errorCode.substring(0, errorCode.lastIndexOf(":"));
        	}
        	finalResult = errorCode;
        	}
        }
        return finalResult;
    }

    /**
     * 向数据库添加数据
     * 
     * @param key
     *            检索字段
     * @param value
     *            数据值
     */
    public void addData(String key, String value) {
        if (dbHelper_ != null && key != null) {
            dbHelper_.addData(key, value);
        }
    }

    /**
     * 将数据插入到数据库中(不判断当前key是否已存在，可能出现两个key同时存在的情况)
     * 
     * @param key
     * @param value
     */
    public void insertData(String key, String value) {
        if (dbHelper_ != null) {
            dbHelper_.insertData(key, value);
        }
    }

    /**
     * 覆盖数据库中已有数据
     * 
     * @param key
     * @param value
     */
    public void updateData(String key, String value) {
        if (dbHelper_ != null) {
            dbHelper_.updateData(key, value);
        }
    }

    /**
     * 从数据库中获取数据，返回数据库中与键值匹配的数据
     * @param key
     * @return
     */
    public String getData(String key) {
        String data = null;
        if (dbHelper_ != null) {
            data = dbHelper_.getData(key);
        }
        return data;
    }
    
    /**
     * 从数据库中删除数据
     * @param key
     * @return 删除成功返回true，
     */
    public boolean deleteData(String key) {
        boolean isSuccess = false;
        if (dbHelper_ != null) {
            isSuccess = dbHelper_.deleteData(key);
        }
        return isSuccess;
    }
    
    /**
     * 将内容保存到SharePrefrence中
     * @param key
     * @param value
     */
    public void saveSP(String key ,String value){
		if(null != key){
			PackageManagerAndroid.ANDROIDDB.save(key, value);
		} 
    }
    
    /**
     * 从SharePrefrence中读取保存的值
     * @param key
     * @return
     */
    public String getSP(String key){
		String temp = PackageManagerAndroid.ANDROIDDB.get(key);
		if(temp == null || "".equalsIgnoreCase(temp)){
			temp = null;
		}
		return temp;
    }
}
